<?php

namespace app\admin\controller\main;

use app\common\controller\AdminController;
use app\common\model\Article as Model;
use app\common\model\ArticleAttribute;
use app\common\model\ArticleCategory;
use app\user\model\User;
use QL\Ext\DImage;
use think\App;

/**
 * @ControllerAnnotation(title="文章管理")
 * Class Article
 * @package app\admin\controller\main
 */
class Article extends AdminController
{

    use \app\admin\traits\Curd;
    protected $allowModifyFields = [
        'status',
        'is_ad',
        'category_id',
        'is_carousel',
        'is_top',
        'is_essence'
    ];

    /**
     * 初始化方法
     */
    public function __construct(App $app)
    {
        parent::__construct($app);
        parent::initialize();
        $this->model = new Model();
        $cateTree = (new ArticleCategory())->tree();

        $this->assign('category_level_list', $cateTree);
    }


    /**
     * @NodeAnotation(title="列表")
     */
    public function index()
    {
        if ($this->request->isAjax()) {
            if (input('selectFields')) {
                return $this->selectList();
            }
            [$page, $limit, $where] = $this->buildTableParames();

            $count = $this->model->where($where)->count('status');
            $list = $this->model
                ->where($where)
                ->page($page, $limit)
                ->order($this->sort)
                ->field('id,sort,title,check_status,view,category_id,status,is_ad,is_carousel,is_top,is_essence,create_time')
                ->select();

            $data = [
                'code' => 0,
                'msg' => '',
                'count' => $count,
                'data' => $list,
            ];
            return json($data);
        }

        $pidCateList = ArticleCategory::getPidCateList();

        $this->assign('pidCateListJson', json_encode(['data' => $pidCateList]));
        return $this->fetch();
    }

    /**
     * @NodeAnotation(title="奖励表")
     */
    public function reward()
    {
        if ($this->request->isAjax()) {
            if (input('selectFields')) {
                return $this->selectList();
            }
            [$page, $limit, $where] = $this->buildTableParames();
            $model = new ArticleAttribute();
            $where[] = ['reward_status', '<>', -1];
            $count = $model->where($where)->count('article_id');
            $list = $model
                ->where($where)
                ->page($page, $limit)
                ->order($this->sort)
                ->field('id,article_id,reward_account,reward_amount,reward_result,reward_name')
                ->select();

            //用户信息
            if ($list) {
                $list=$list->toArray();
                $aids=array_column($list,'article_id');
                $articles=(new Model())->whereIn('id',$aids)->column('title,user_id,create_time','id');

                $uids=array_column($articles,'user_id');


                $users = (new User())->whereIn('id',$uids)->column('username','id');
                foreach ($list as &$v){
                    $article=$articles[$v['article_id']];
                    $v['username']=$users[$article['user_id']];
                    $v['create_time']=date('Y-m-d H:i:s',$article['create_time']);
                    $v['title']=$article['title'];
                }

         }
            $data = [
                'code' => 0,
                'msg' => '',
                'count' => $count,
                'data' => $list,
            ];
            return json($data);
        }


        return $this->fetch();
    }

    public function reward_detail($id)
    {
        $row = (new ArticleAttribute())->find($id);
        $this->assign('row',$row);
        return $this->fetch();
    }

    /**
     * @NodeAnotation(title="编辑")
     */
    public function add()
    {
        if ($this->request->isAjax()) {
            $post = $this->request->post();
            try {
                if ($post['publish_time'] > date('Y-m-d H:i:s')) {
                    $post['status'] = 0; //定时发布
                } else {
                    $post['publish_time'] = date('Y-m-d H:i:s');
                    $post['status'] = 1;
                }
                $content = html_entity_decode($post['content']);
                if ($post['downpic']) {
                    $post['content'] = (new DImage())->run([
                        'content' => $content,
                        'www_root' => $_SERVER['DOCUMENT_ROOT'],
                        'image_path' => '/uploads/' . date('Y') . '/' . date('md'),
                    ]);
                }
                if ($post['content'] && (!$post['keywords'] || !$post['cover_img'] || !$post['description'])) {

                    $CDK = Model::getCDK($content, $post['title']);
                    if (!$post['keywords'] && $CDK['K']) {
                        $post['keywords'] = $CDK['K'];
                    }
                    if (!$post['cover_img'] && $CDK['C']) {
                        $post['cover_img'] = $CDK['C'];
                    }
                    if (!$post['description'] && $CDK['D']) {
                        $post['description'] = $CDK['D'];
                    }
                }
                if ($post['title'] && !$post['seo_title']) {
                    $post['seo_title'] = $post['title'];
                }
                $save = $this->model->createNew($post);
            } catch (\Exception $e) {
                $this->error('保存失败' . $e->getMessage());
            }
            $save ? $this->success('保存成功') : $this->error('保存失败');
        }

        return $this->fetch();
    }

    /**
     * @NodeAnotation(title="编辑")
     */
    public function edit($id = '')
    {
        if (!$id) {
            $id = request()->param()['id'];
        }
        $attributeModel = new ArticleAttribute();
        $row = $this->model->find($id);
        $attribute = $attributeModel->where('article_id', $id)->find();
        $item = $row->toArray() + ($attribute ? $attribute->toArray() : []);
        empty($row) && $this->error('数据不存在');
        if ($this->request->isAjax()) {
            $post = $this->request->post();
            if (isset($post['check_status']) && $post['check_status'] == 1) {
                $post['status'] = 1;
            } elseif ($post['publish_time'] > date('Y-m-d H:i:s')) {
                $post['status'] = 0; //定时发布
            }
            if (!$post['publish_time']) {
                $post['publish_time'] = date('Y-m-d H:i:s');
            }
            $content = htmlspecialchars_decode($post['content']);
//            dd($content);
            if ($post['downpic']) {
                $post['content'] = (new DImage())->run([
                    'content' => $content,
                    'www_root' => $_SERVER['DOCUMENT_ROOT'],
                    'image_path' => '/uploads/' . date('Y') . '/' . date('md'),
                ]);
            }
            if ($post['content'] && (!$post['keywords'] || !$post['cover_img'] || !$post['description'])) {

                $CDK = Model::getCDK($content, $post['title']);
                if (!$post['keywords'] && $CDK['K']) {
                    $post['keywords'] = $CDK['K'];
                }
                if (!$post['cover_img'] && $CDK['C']) {
                    $post['cover_img'] = $CDK['C'];
                }
                if (!$post['description'] && $CDK['D']) {
                    $post['description'] = $CDK['D'];
                }
            }
            if ($post['title'] && !$post['seo_title']) {
                $post['seo_title'] = $post['title'];
            }
            if (isset($post['reward_amount']) && $post['reward_amount']) {
                $post['reward_status'] = 1;
            }
            $this->model->filterFields($post, $mainData, $attributeData, $otherData);
            try {
                $save = $row->save($mainData);
                if (!$attribute) {
                    $attribute = $attributeModel;
                    $attributeData['article_id'] = $id;
                }
                $attribute->save($attributeData);
                if (isset($otherData['attachlink'])) {
                    $attach = $otherData['attachlink'];
                    $attach['subject_id'] = $id;
                    $attach['subject'] = 'ARTICLE';
                    hooks('attachlink.link_save', $attach);
                }
            } catch (\Exception $e) {
                $this->error($e->getMessage());
            }
            $save ? $this->success('保存成功') : $this->error('保存失败');
        }
        $refuse_tpl = sysconfig('article.refuse_tpl');
        if ($refuse_tpl) {
            $refuse_tpl = json_encode(explode("\n", $refuse_tpl));
        }

        $this->assign('refuseTpl', $refuse_tpl);
        if (isset($item['content'])) {
            $item['content'] = html_entity_decode(htmlspecialchars_decode($item['content']));
        }
        $this->assign('row', $item);
        return $this->fetch();
    }

    public function changeCategory()
    {
        $data = $this->request->param();
        $ids = $data['id'];
        $this->model->whereIn('id', $ids)->save(['category_id' => $data['category_id']]);
        return json(['code' => 1, 'msg' => '修改成功']);
    }

}